package com.ruoyi.livedemo.mapper;

import com.ruoyi.livedemo.dto.DiaryMoodCount;
import com.ruoyi.livedemo.entity.DiaryEntry;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

@Mapper
public interface DiaryEntryMapper {

    @Select("SELECT * FROM diary_entries WHERE user_id=#{userId} " +
            "ORDER BY entry_date DESC, id DESC " +
            "LIMIT #{limit} OFFSET #{offset}")
    List<DiaryEntry> findPage(@Param("userId") Long userId,
                              @Param("offset") int offset,
                              @Param("limit") int limit);

    @Select("SELECT COUNT(1) FROM diary_entries WHERE user_id=#{userId}")
    long countByUser(Long userId);

    @Select("SELECT COALESCE(NULLIF(TRIM(mood), ''), '未填写') AS mood, COUNT(*) AS total " +
            "FROM diary_entries WHERE user_id=#{userId} " +
            "GROUP BY COALESCE(NULLIF(TRIM(mood), ''), '未填写')")
    List<DiaryMoodCount> countMoodByUser(Long userId);

    @Select("SELECT * FROM diary_entries WHERE id=#{id} AND user_id=#{userId}")
    DiaryEntry findByIdAndUser(@Param("id") Long id, @Param("userId") Long userId);

    @Insert("INSERT INTO diary_entries (user_id, entry_date, title, weather, mood, content, gratitude, cover_path) " +
            "VALUES (#{userId}, #{entryDate}, #{title}, #{weather}, #{mood}, #{content}, #{gratitude}, #{coverPath})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(DiaryEntry entry);

    @Update("UPDATE diary_entries SET entry_date=#{entryDate}, title=#{title}, weather=#{weather}, " +
            "mood=#{mood}, content=#{content}, gratitude=#{gratitude}, cover_path=#{coverPath} " +
            "WHERE id=#{id} AND user_id=#{userId}")
    int update(DiaryEntry entry);

    @Delete("DELETE FROM diary_entries WHERE id=#{id} AND user_id=#{userId}")
    int delete(@Param("id") Long id, @Param("userId") Long userId);
}
